﻿using System;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Xml.Linq;
using Cjc.Calculation.ExpressionEngine;

namespace SilverlightApplication1
{
	public partial class Page : UserControl
	{
		private Engine engine;
		private Worksheet worksheet;
		private SolidColorBrush expColor = new SolidColorBrush( Colors.Green );

		public Page()
		{
			InitializeComponent();

			try
			{
				engine = new Engine();
				worksheet = engine.CreateWorksheet();

				//			engine = new Engine();
				//			worksheet = new Worksheet( engine );

				engine[ "A1" ].ExpressionText = "( 1280 * 1024 / 8 ) + A2";
				engine[ "A2" ].ExpressionText = "42 * A3";
				worksheet[ "A3" ].Value = 20.2d;
				worksheet[ "A4" ].Value = 50d;
				worksheet[ "A5" ].Formula.ExpressionText = "SUM( A3:A4 )";
				engine[ "B6" ].ExpressionText = "42 * 5";
				engine[ "B7" ].ExpressionText = "B6";

				var result0 = worksheet[ "B6" ].Value;
				var result1 = worksheet[ "B7" ].Value;
				var result2 = worksheet[ "A1" ].Value;
				var result3 = worksheet[ "A2" ].Value;
				var result4 = worksheet[ "A5" ].Value;
				var result5 = worksheet.Evaluate( "B8 = A1" );
				var result6 = worksheet.Evaluate( "B8" );

				worksheet[ "myvalue" ].Formula.ExpressionText = "A1";
				var result7 = worksheet[ "myvalue" ].Value;

				worksheet[ "A3" ].Value = 25;
				var result8 = worksheet.Evaluate( "A1" );
			}
			catch ( Exception ex )
			{
				AddResult( ex );
			}
		}

		private void evaluate_Click( object sender, System.Windows.RoutedEventArgs e )
		{
			resultsList.Items.Add( new TextBlock { Text = "> " + expressionBox.Text, Foreground = expColor } );

			try
			{
				AddResult( worksheet.Evaluate( expressionBox.Text ) );
			}
			catch ( Exception ex )
			{
				AddResult( ex );
			}

			expressionBox.SelectAll();
			expressionBox.Focus();
		}

		private void AddResult( object value )
		{
			var typeName = ( value != null ) ? value.GetType().ToString() : "null";
			var result = ( value is Exception ) ? ( (Exception)value ).Message : value;

			var item = new TextBlock
			{
				Text = string.Format( "({0}) {1}", typeName, result )
			};

			resultsList.Items.Add( item );
			resultsList.SelectedItem = item;
			resultsList.UpdateLayout();
			resultsList.ScrollIntoView( resultsList.SelectedItem );
		}

		private void expressionBox_KeyDown( object sender, System.Windows.Input.KeyEventArgs e )
		{
			if ( e.Key == Key.Enter ) evaluate_Click( sender, e );
		}

		private void expressionBox_Loaded( object sender, System.Windows.RoutedEventArgs e )
		{
			expressionBox.SelectAll();
			expressionBox.Focus();
		}
	}
}